package com.youi.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
/**
 * 短信发送工具类
 * @author  erdong.Chan
 *
 */
public class SmsUtil {
	
	
	
	public  static Boolean sendMessage(String content,String phone){
		try {
			String urlStr="http://115.28.105.110/";
			URL url=new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setUseCaches(false); //Post 请求不能使用缓存
			urlConnection.setInstanceFollowRedirects(true);
			urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			urlConnection.setRequestProperty("Charset", "UTF-8"); 
			urlConnection.connect();
			
	        DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
	        String params="code="+content+"&phone="+phone;
	        out.writeBytes(params);
	        out.flush();
	        out.close(); 
	        
	        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
	        
	        String line;
	        String responseStr="";
	        while ((line = reader.readLine()) != null){
	        	responseStr+=line;	
	        }
	        System.out.println("调用短信接口返回数据["+responseStr+"]");
	        reader.close();
	        urlConnection.disconnect();
	        if(responseStr.contains("\"msg\":1")){
	        	return true;
	        }
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return false;
	}
	
	public  static String getRandom(Integer num){
		////int code=new Random().nextInt(9999-1000+1)+1000;	//4位数验证码
		String code="";
		Random random=new Random();
		for (int i = 0; i < num; i++) {
			code+=random.nextInt(10);
		}
		return code;
	}
	
	public  static String getRandomLetter(Integer num){
		char[] codeSequence = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
				'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
				'x', 'y', 'z', };
		String code="";
		Random random=new Random();
		for (int i = 0; i < num; i++) {
			code+=codeSequence[random.nextInt(26)];
		}
		return code;
	}
	
	
	public static void main(String[] args) {
		
		sendMessage("测试2015", "18520040243");
	}
	

	
}
